package com.ithema.notebook.data;

import com.ithema.notebook.notify.NotifyType;
import com.ithema.notebook.notify.SystemNotify;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.Collections;

/**
 * Package: com.ithema.notebook.data
 * Description：jtable工具
 *
 * @author: huangjian
 * Date:  2020/10/19 11:25
 * Modified By:
 */
public class JTableUtils {

    /**
     * 选中行往上移动一行
     *
     * @param table       表格对象
     * @param model       表格模型对象
     * @param columnCount 表格的列数一共有多少列
     * @author liunan
     */
    public static void moveUpRow(JTable table, DefaultTableModel model, int columnCount) {
        int row = table.getSelectedRow();
        if (row == -1) {
            SystemNotify.notify(NotifyType.REMOVE_CONTENT_SELECT_NULL);
        } else if (row == 0) {
            SystemNotify.notify(NotifyType.MOVE_CONTENT_SELECT_TOP);
        } else {
            Object[] obj = new Object[columnCount];
            for (int i = 0; i < columnCount; i++) {
                obj[i] = table.getValueAt(row, i);
            }
            model.removeRow(row);
            model.insertRow(row - 1, obj);

            Collections.swap(DataCenter.NOTE_LIST,row,row-1);
        }
    }


    /**
     * 选中行往下移动一行
     *
     * @param table       表格对象
     * @param model       表格模型对象
     * @param columnCount 表格的列数一共有多少列
     * @author liunan
     */
    public static void moveDownRow(JTable table, DefaultTableModel model, int columnCount) {
        int row = table.getSelectedRow();
        if (row == -1) {
            SystemNotify.notify(NotifyType.REMOVE_CONTENT_SELECT_NULL);
        } else if (row == table.getRowCount() - 1) {
            SystemNotify.notify(NotifyType.MOVE_CONTENT_SELECT_BOTTOM);
        } else {
            Object[] obj = new Object[columnCount];
            for (int i = 0; i < columnCount; i++) {
                obj[i] = table.getValueAt(row, i);
            }
            model.removeRow(row);
            model.insertRow(row + 1, obj);
            Collections.swap(DataCenter.NOTE_LIST,row,row+1);
        }
    }
}
